package cn.lanjh.auth.service.impl;


import cn.lanjh.auth.constants.AuthConstants;
import cn.lanjh.common.security.OpenUserDetails;
import cn.lanjh.system.domain.SysUser;
import cn.lanjh.system.feign.RemoteRoleService;
import cn.lanjh.system.feign.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Security用户信息获取实现类
 *
 * @author liuyadu
 */
@Slf4j
@Service("userDetailService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private RemoteRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        SysUser sysUser = userService.selectSysUserByUsername(username);
        if (sysUser == null || sysUser.getUserId() == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        Long userId = sysUser.getUserId();
        String password = sysUser.getPassword();
        String nickName = sysUser.getUserName();
        String avatar = sysUser.getAvatar();
        boolean accountNonLocked = Integer.parseInt(sysUser.getStatus()) != AuthConstants.ACCOUNT_STATUS_LOCKED;
        boolean credentialsNonExpired = true;
        boolean enabled = Integer.parseInt(sysUser.getStatus()) == AuthConstants.ACCOUNT_STATUS_NORMAL ? true : false;
        boolean accountNonExpired = true;
        OpenUserDetails userDetails = new OpenUserDetails();
        //userDetails.setDomain(domain);
        //userDetails.setAccountId(accountId);
        userDetails.setUserId(userId);
        userDetails.setUsername(username);
        userDetails.setPassword(password);
        userDetails.setNickName(nickName);
        //userDetails.setAuthorities(account.getAuthorities());
        userDetails.setAvatar(avatar);
        //userDetails.setAccountId(accountId);
        userDetails.setAccountNonLocked(accountNonLocked);
        userDetails.setAccountNonExpired(accountNonExpired);
        //userDetails.setAccountType(accountType);
        userDetails.setCredentialsNonExpired(credentialsNonExpired);
        userDetails.setEnabled(enabled);
        //userDetails.setClientId(clientProperties.getOauth2().get("admin").getClientId());
        return userDetails;
    }
}
